<!doctype html>
<html><head>
<meta charset="utf-8">
<title>亿欧关键词工具</title>
<script src="lib/jquery-2.1.4.min.js"></script>
<link rel="stylesheet" href="lib/zTreeStyle.css" type="text/css">
<script type="text/javascript" src="lib/jquery.ztree.core-3.5.min.js"></script>
<script type="text/javascript" src="lib/jquery.ztree.exedit-3.5.min.js"></script>
<SCRIPT type="text/javascript">
	var boolean=true;
	var setting = {
		view: {
			addHoverDom: addHoverDom,
			removeHoverDom: removeHoverDom,
			selectedMulti: false
		},
		edit: {
			enable: true,
			editNameSelectAll: true,

		},
		data: {
			simpleData: {
				enable: true
			}
		},
		callback: {
			beforeDrag: zTreeBeforeDrag,
			beforeEditName: beforeEditName,
			beforeRemove: beforeRemove,
			beforeRename: beforeRename,
			onRemove: onRemove,
			onRename: onRename,
			onClick: zTreeOnClick
		}
	};

	var log, className = "dark";
	function zTreeBeforeDrag(treeId, treeNodes) {
		 return false;
	};
	function beforeEditName(treeId, treeNode) {
		className = (className === "dark" ? "":"dark");			
		var zTree = $.fn.zTree.getZTreeObj("treeDemo");
		zTree.selectNode(treeNode);
		/*var psw=prompt("修改名称，请输入密码","");
		if(psw=="335335")
			return true;
		else
			return false;*/
		return true;
	}
	function beforeRemove(treeId, treeNode) {
		className = (className === "dark" ? "":"dark");
		var zTree = $.fn.zTree.getZTreeObj("treeDemo");
		zTree.selectNode(treeNode);
		/*var psw=prompt("删除后将不能恢复，确认删除请输入密码","");
		if(psw=="335335")
			return true;
		else
			return false;*/
		return true;
	}
	function onRemove(e, treeId, treeNode) {
		$.ajax({  
			type: "post",  
			url: "manageCategory.php",  
			dataType: "json",  
			data:{    
             id:treeNode.id,
			 pId:1,
			 name:treeNode.name  
    		},
			success: function(msg){  
				alert(msg);
			},
			error:function(XMLResponse){alert(XMLResponse.responseText)} 	
		});
	}
	function beforeRename(treeId, treeNode, newName, isCancel) {
		className = (className === "dark" ? "":"dark");			
		if (newName.length == 0) {
			alert("节点名称不能为空.");
			var zTree = $.fn.zTree.getZTreeObj("treeDemo");
			setTimeout(function(){zTree.editName(treeNode)}, 10);
			return false;
		}
		return true;
	}
	function onRename(e, treeId, treeNode, isCancel) {
		$.ajax({  
			type: "post",  
			url: "manageCategory.php",  
			dataType: "json",  
			data:{    
             id:treeNode.id,
			 name:treeNode.name  
    		},
			success: function(msg){  
				alert(msg.message);
			} 		
		});
		window.setTimeout(function(){window.location.reload()},1500);
	}
	function zTreeOnClick(event, treeId, treeNode) {
		$("#category").val(treeNode.id);
	};

	var newCount = 1;
	function addHoverDom(treeId, treeNode) {
		var sObj = $("#" + treeNode.tId + "_span");
		if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;
		var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
			+ "' title='add node' onfocus='this.blur();'></span>";
		sObj.after(addStr);
		var btn = $("#addBtn_"+treeNode.tId);
		if (btn) btn.bind("click", function(){
			/*var psw=prompt("添加分类，请输入密码","");
			if(psw!="335335")
				return false;*/
			var zTree = $.fn.zTree.getZTreeObj("treeDemo");
			zTree.addNodes(treeNode, {id:(100 + newCount), pId:treeNode.id, name:"新类别"});
			$.ajax({  
			  type: "post",  
			  url: "manageCategory.php",  
			  dataType: "json",  
			  data:{    
			   pId:treeNode.id, 
			  },
			  success: function(msg){  
				alert(msg.message);
			} 	 			  
		  	});
			window.setTimeout(function(){window.location.reload()},1500);
			return false;
		});
	};
	function removeHoverDom(treeId, treeNode) {
		$("#addBtn_"+treeNode.tId).unbind().remove();
	};
	function selectAll() {
		var zTree = $.fn.zTree.getZTreeObj("treeDemo");
		zTree.setting.edit.editNameSelectAll =  $("#selectAll").attr("checked");
	}
	
	$(document).ready(function(){
		var zNodes=$("#as").val();
		$.fn.zTree.init($("#treeDemo"), setting, eval(zNodes));
		$("#selectAll").bind("click", selectAll);
		$("#theme").focusout(function(e) {
            alert($("#theme").val());
        });
	});
	function checkForm(){
		var id=$("#category").val();
		var theme=$("input[name='theme']").val();
		var keyWords=$("textarea[name='keyWords']").val();
		if(id==""||theme==""||keyWords==""){
			alert("请输入主题，关键词和选择分类！");
			return false;
		}else
			return true;
	}
	function checkFile(){
		var file=$("input[type='file']").val();
		if(file==''){
			alert("请选择文件！");
			return false;
		}
		return true;
	}
</SCRIPT>
<style type="text/css">
.ztree li span.button.add {margin-left:2px; margin-right: -1px; background-position:-144px 0; vertical-align:top; *vertical-align:middle}
h2,h3{
	display:inline;
}
a{
	text-decoration:none;
	color:#000;
}
a:hover{
	text-decoration:underline;
}
.red{
	color:#F00;
}
#leibie{
	position:absolute;
	left:450px;
}
textarea{
	resize: none;
	width:400px;
	border-radius: 5px;
	font-size:18px;
}
input[name="theme"]{
	border-radius: 5px;
	width:400px;
}
header{
	margin-bottom:20px;
	margin-top:10px;
}
header h3{
	margin-right:5px;
	display:inline;
}
#left section{
	margin-bottom:10px;
}
#content{
	margin-left:10px;
	font-size:18px;
}
#result textarea{
	height:100px;
}
input[type="submit"]{
	width:70px;
	height:30px;
}
#import{
	margin-top:20px;
}
#import section a{
	color:red;
	position:relative;
	top:-20px;
}
</style>
</head>

<body>
<?php
function TrimArray($Input){   //清除数组中元素的左右空格
    if (!is_array($Input))
        return trim($Input);
    return array_map('TrimArray', $Input);
}



$category = !empty($_POST['category']) ? trim($_POST['category']) : null;
$theme = !empty($_POST['theme']) ? trim($_POST['theme']) : null;
$keyWords = !empty($_POST['keyWords']) ? trim($_POST['keyWords']) : null;
$num=!empty($_POST['num']) ? trim($_POST['num']) : null;
$result=null;


require('inc/MYSQL_Connection.php');
if($category!=null&&$theme!=null&&$keyWords!=null){
	$keyWords=addslashes($keyWords);  //重新格式化 stripslashes()会反格式化
	$keysArray=explode("\n",$keyWords);
	$keysArray = TrimArray($keysArray);  //清除数组中元素的左右空格
	$str="";
	$SofA=sizeof($keysArray);
	switch($num){
		case 2:				//分割成2个{}
			if($SofA>1){
				$str='{'.implode(',',array_slice($keysArray,0,intval($SofA/2))).'},';
				$str=$str.'{'.implode(',',array_slice($keysArray,intval($SofA/2))).'}';
			}else
				$str='{'.$keyWords.'}';
			break;
		case 3:	
			$yushu=$SofA%3;			              //分割成3个{}
			if($SofA>2){							
				if(--$yushu>=0)
					$str='{'.implode(',',array_slice($keysArray,0,intval($SofA/3))).','.$keysArray[($SofA-1)].'},';
				else
					$str='{'.implode(',',array_slice($keysArray,0,intval($SofA/3))).'},';
				if(--$yushu>=0)
					$str=$str.'{'.implode(',',array_slice($keysArray,intval($SofA/3),intval($SofA/3))).','.$keysArray[($SofA-2)].'},';
				else
					$str=$str.'{'.implode(',',array_slice($keysArray,intval($SofA/3),intval($SofA/3))).'},';
				$str=$str.'{'.implode(',',array_slice($keysArray,2*intval($SofA/3),intval($SofA/3))).'}';
			}else{
				if(--$yushu>=0)
					$str='{'.$keysArray[0].'}';
				if(--$yushu>=0)
					$str=$str.',{'.$keysArray[1].'}';
			}
			break;
		case 4:
			$yushu=$SofA%4;		
			if($SofA>3){
				if(--$yushu>=0)
					$str='{'.implode(',',array_slice($keysArray,0,intval($SofA/4))).','.$keysArray[($SofA-1)].'},';
				else
					$str='{'.implode(',',array_slice($keysArray,0,intval($SofA/4))).'},';
				if(--$yushu>=0)
					$str=$str.'{'.implode(',',array_slice($keysArray,intval($SofA/4),intval($SofA/4))).','.$keysArray[($SofA-2)].'},';
				else	
					$str=$str.'{'.implode(',',array_slice($keysArray,intval($SofA/4),intval($SofA/4))).'},';
				if(--$yushu>=0)
					$str=$str.'{'.implode(',',array_slice($keysArray,2*intval($SofA/4),intval($SofA/4))).','.$keysArray[($SofA-3)].'},';
				else	
					$str=$str.'{'.implode(',',array_slice($keysArray,2*intval($SofA/4),intval($SofA/4))).'},';
				$str=$str.'{'.implode(',',array_slice($keysArray,3*intval($SofA/4),intval($SofA/4))).'}';
			}else{
				if(--$yushu>=0)
					$str='{'.$keysArray[0].'}';
				if(--$yushu>=0)
					$str=$str.',{'.$keysArray[1].'}';
				if(--$yushu>=0)
					$str=$str.',{'.$keysArray[2].'}';
			}
			break;
		case 5:
			$yushu=$SofA%5;
			if($SofA>4){
				if(--$yushu>=0)
					$str='{'.implode(',',array_slice($keysArray,0,intval($SofA/5))).','.$keysArray[($SofA-1)].'},';
				else	
					$str='{'.implode(',',array_slice($keysArray,0,intval($SofA/5))).'},';
				if(--$yushu>=0)
					$str=$str.'{'.implode(',',array_slice($keysArray,intval($SofA/5),intval($SofA/5))).','.$keysArray[($SofA-2)].'},';
				else
					$str=$str.'{'.implode(',',array_slice($keysArray,intval($SofA/5),intval($SofA/5))).'},';
				if(--$yushu>=0)
					$str=$str.'{'.implode(',',array_slice($keysArray,2*intval($SofA/5),intval($SofA/5))).','.$keysArray[($SofA-3)].'},';
				else
					$str=$str.'{'.implode(',',array_slice($keysArray,2*intval($SofA/5),intval($SofA/5))).'},';
				if(--$yushu>=0)
					$str=$str.'{'.implode(',',array_slice($keysArray,3*intval($SofA/5),intval($SofA/5))).','.$keysArray[($SofA-4)].'},';
				else
					$str=$str.'{'.implode(',',array_slice($keysArray,3*intval($SofA/5),intval($SofA/5))).'},';
				$str=$str.'{'.implode(',',array_slice($keysArray,4*intval($SofA/5),intval($SofA/5))).'}';
			}else{
				if(--$yushu>=0)
					$str='{'.$keysArray[0].'}';
				if(--$yushu>=0)
					$str=$str.',{'.$keysArray[1].'}';
				if(--$yushu>=0)
					$str=$str.',{'.$keysArray[2].'}';
				if(--$yushu>=0)
					$str=$str.',{'.$keysArray[3].'}';
			}
			break;
		default:
			echo '大括号数量没有选好！';
	}
	if(mysqli_connect_errno()){
		echo "<span style='color:#F00'> 数据库连接失败！</span>";
	}else{
		$db->query("set names utf8");     //解决乱码
		$query="insert into keywords values('',".$category.",'".$theme."','".$str."')";
		$result=$db->query($query);
		
	}
}
?>
<div id="content">
	<header>
        <h3>关键词入库</h3>
        <h3><a href="findKeyWords.php">关键词查询</a></h3>
        <h3><a href="keywords.php">关键词处理</a></h3>
        <hr>
    </header>
    <div id="leibie">
        <span class="red">*</span>Ⅱ.所属类别：<br>
        <div class="zTreeDemoBackground left">
            <ul id="treeDemo" class="ztree"></ul>
        </div>
    </div>
    <div id="left">
    	<form action="makeKeyWords.php" method="post" onSubmit="return checkForm()">
          <section>
          	<input type="hidden" name="category" id="category">
            <span class="red">*</span>Ⅰ.主题：<br><input type="text" name="theme" id="theme">
          </section>
          <section>
          	<span class="red">*</span>Ⅲ.关键词：<br><textarea name="keyWords" rows="10"></textarea></section>
          <section>
          	<span class="red">*</span>Ⅳ.大括号数量：<input type="radio" name="num" value="2">2&nbsp;<input type="radio" name="num" value="3" checked>3&nbsp;<input type="radio" name="num" value="4">4&nbsp;<input type="radio" name="num" value="5">5
          </section>
          <br><input type="submit" value="Ⅴ.提交">
        </form>
    </div>
  <div id="import">
    	<form action="import.php" method="post" enctype="multipart/form-data" id="importFileForm" onSubmit="return checkFile()">
            <label for="file">导入文件:</label>
            <input type="file" name="file" id="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"/> 
            <input type="submit" name="submit" value="导入" />
        </form>
     <br>
    <section><a href="upload/temp/test.xlsx">模板下载</a></section>
    </div>
</div>
<div id="result">
<?php
if($result===TRUE){
	echo "<span class='red'>插入数据库成功！</span><br><textarea id='keywords' readonly>$str</textarea>";
}
if($result===false){
	echo "<span class='red'>插入数据库失败！</span><br>".$str;	
}
if(mysqli_connect_errno()){
	echo "<span style='color:#F00'> 数据库连接失败！</span>";
}else{
	$db->query("set names utf8");      //解决乱码
	$query2="select * from keywordscategory";   //查询分类
	$result2=$db->query($query2);	
	if($result2->num_rows>0){
		$zNodes='[';
		for($i=0;$i<$result2->num_rows;$i++){
			$row=$result2->fetch_assoc();
			$zNodes=$zNodes.'{ id:'.$row['id'].', pId:'.$row['pId'].', name:"'.$row['id']."--".$row['name'].'"},';
		}
		$zNodes = substr($zNodes,0,strlen($zNodes)-1); 
		$zNodes=$zNodes.']';
	}else
		$zNodes='[{id:1, pId:0, name:"查无数据！"}]';	
	echo "<div style='display:none'><textarea id='as'>".$zNodes."</textarea></div>";
	$result2->free();	
}	
$db->close();			
?>
</div>
</body>
</html>